import requests
import time


class BinarySearchClient:
    def __init__(self, base_url="http://localhost:8000"):
        self.base_url = base_url

    def search(self, sorted_array: list, target: int) -> dict:
        """执行二分查找"""
        try:
            response = requests.post(
                f"{self.base_url}/binary_search",
                json={
                    "sorted_array": sorted_array,
                    "target": target
                },
                timeout=5.0
            )
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            print(f"请求失败: {str(e)}")
            raise


def run_demo():
    client = BinarySearchClient()

    test_cases = [
        {"array": [1, 3, 5, 7, 9], "target": 5},
        {"array": [2, 4, 6, 8, 10], "target": 7},
        {"array": list(range(1000000)), "target": 999999}
    ]

    print("二分查找演示")
    print("=" * 40)
    for case in test_cases:
        print(f"在数组{case['array'][:5]}...中查找{case['target']}")
        start = time.time()
        result = client.search(case["array"], case["target"])
        elapsed = time.time() - start

        if result["found"]:
            print(f"找到目标，索引: {result['index']}")
        else:
            print("未找到目标")
        print(f"迭代次数: {result['iterations']}")
        print(f"耗时: {elapsed:.6f}秒\n")


if __name__ == "__main__":
    run_demo()